package com.exam.api.common.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Optional;

/**
 * @Author 北橙
 * @Create 2022/4/27
 * @Description 请求上下文
 */
public class RequestContextUtil {

    public static Optional<HttpServletRequest> getRequest() {
        Optional<ServletRequestAttributes> requestAttributesOptional = getServletRequestAttributes();
        return requestAttributesOptional.map(ServletRequestAttributes::getRequest);
    }

    public static Optional<HttpServletResponse> getResponse() {
        Optional<ServletRequestAttributes> requestAttributesOptional = getServletRequestAttributes();
        return requestAttributesOptional.map(ServletRequestAttributes::getResponse);
    }

    public static Optional<ServletRequestAttributes> getServletRequestAttributes() {
        Optional<RequestAttributes> attributesOptional = getRequestAttributes();
        return attributesOptional.map(requestAttributes -> (ServletRequestAttributes) requestAttributes);
    }

    public static Optional<RequestAttributes> getRequestAttributes() {
        return Optional.ofNullable(RequestContextHolder.getRequestAttributes());
    }
}
